<template>
  <a-spin :spinning="loading">

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="margin-top: 5px">
      <a-button @click="modelFormHandle(
          { questionId: queryParam.questionId, sort: dataList.length }
          )" type="primary" icon="plus">添加题目</a-button>
      <a-button @click="modelUploadHandle" icon="plus">导入题目</a-button>
      <a-button type="link" >题目总数: {{ dataList.length }}</a-button>
    </div>

    <div id="list">
      <a-row type="flex" align="middle" justify="end"
             style="padding: 10px; background-color: #F8F8F8; margin-bottom: 10px;"
             v-for="(item, index) in dataList" :key="index">
        <a-col :span="1" class="allowDrag" style="text-align: center; cursor: pointer">
          <a-icon type="more" />
        </a-col>

        <a-col :span="23" style="padding-bottom: 10px; border-bottom: 1px solid #ccc;">
          <div class="is-rating" v-if="item.isRating === 2">
            <a-button type="primary" shape="round" size="small">不计分</a-button>
          </div>
          <h3>{{ Number(index) + 1 + '. ' + item.assessDetail }}</h3>

          选项：
          <div style="display: inline-block; margin: 0 10px;" v-for="(o, i) in item.assessItem.split(',')" :key="i">
            {{ o }}
          </div>




        </a-col>
        <div>
          <a-button type="link" @click="modelFormHandle(item)">编辑</a-button>
          <a-popconfirm title="确定删除吗?" @confirm="() => deleteHandle(item.id)" okText="确定" cancelText="取消">
            <a>删除</a>
          </a-popconfirm>
        </div>
      </a-row>
    </div>

    <title-form v-if="modelFormVisible" ref="modelForm" @load="getList"></title-form>
    <title-upload v-if="modelUploadVisible" ref="modelUpload" @load="getList"></title-upload>
  </a-spin>
</template>

<script>
import titleForm from './title-form'
import titleUpload from './title-upload'
import Sortable from 'sortablejs'
import {getAction, putAction, deleteAction, postAction, postdeleteAction} from '@/api/manage'

export default {
  name: "titles",
  components: {
    titleForm,
    titleUpload
  },
  data () {
    return {
      disableMixinActivated: true,
      modelUploadVisible: false,
      modelFormVisible: false,
      loading: false,
      queryParam: {
        questionId: ''
      },
      dataList: [],
      url: {
        list: '/dimension/getDimension',
        updateSort: '/dimension/updateDimensionSort',
        delete: '/dimension/deleteDimension'
      }
    }
  },
  watch: {
    $route: {
      handler(to, from) {
        //深度监听，同时也可监听到param参数变化
        this.$nextTick(() => {
          // console.log('to', to)
          // console.log('from', from)
          // if (!from) {
            this.queryParam.questionId = to.query.questionId
            Promise.all([
              this.getList()
            ]).then(() => {
              console.log('this.dataList', this.dataList)
            }).catch(res => {
              console.log('res', res)
            })
          // }
        })
      },
      deep: true,
      // 代表在wacth里声明了这个方法之后立即先去执行handler方法
      immediate: true
    }
  },
  mounted () {
    let that = this
    const $el = document.querySelector('#list')
    Sortable.create($el, {
      handle: ".allowDrag",
      animation: 150,
      ghostClass: 'blue-background-class',
      onEnd: function (evt) {
        // 获取排序之后的data数据
        that.dataList.splice(evt.newIndex, 0, that.dataList.splice(evt.oldIndex, 1)[0])
        var newArray = that.dataList.slice(0)
        that.dataList = []
        that.$nextTick(() => {
          that.dataList = newArray
          that.onUpEvent(evt)
        })
      }
    })
  },
  methods: {
    getList() {
      return new Promise((resolve, reject) => {
        this.loading = true
        getAction(this.url.list, this.queryParam).then(res => {
          this.loading = false
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.dataList = [ ...res.result ]
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    deleteHandle(id) {
      if (!this.url.delete) {
        return this.$message.warning("请设置url.delete属性!")
      }
      var that = this;
      this.loading = true
      postdeleteAction(that.url.delete, id).then((res) => {
        if (res.success) {
          this.dataList.forEach(res => {
            if (res.id === id) {
              this.dataList.splice(this.dataList.indexOf(res), 1)
            }
          })
          that.$message.success(res.message);
        } else {
          that.$message.error(res.message);
        }
      }).finally(() => {
        that.loading = false;
      });
    },
    // 新增 / 修改
    modelFormHandle (record) {
      this.modelFormVisible = true
      this.$nextTick(() => {
        this.$refs.modelForm.dataForm = Object.assign({}, record)
        this.$refs.modelForm.init()
      })
    },
    modelUploadHandle () {
      this.modelUploadVisible = true
      this.$nextTick(() => {
        this.$refs.modelUpload.dataForm.questionId = this.queryParam.questionId
        this.$refs.modelUpload.init()
      })
    },
    onUpEvent(evt) {
      console.log('evt', evt)
      this.dataList[evt.oldIndex]['sort'] = evt.oldIndex
      this.dataList[evt.newIndex]['sort'] = evt.newIndex
      const temp = []
      temp[0] = this.dataList[evt.oldIndex]
      temp[1] = this.dataList[evt.newIndex]
      console.log('temp', temp)
      putAction(this.url.updateSort, temp).then(res => {
        if (!res.success) {
          return this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style scoped>
.is-rating {
  position: absolute;
  top: 4px;
  right: 4px;
}

.is-rating a-button span {
  padding: 0 8px;
}
</style>
